#include<iostream>
#include<fstream>
#include<func.h>
#include<string>
#include<vector>
#include<limits>
using std::endl;
using std::cout;
using std::ifstream;
using std::ofstream;
using std::cerr;
using std::string;
using std::vector;
using std::cin;


struct Record{
    string _word;
    int _frequency; //频率
};

class Dictionary{
public:
    void read(const string&filename); //读一个文件
    void reFind(const char*world);//查找单词和频率
    void store(const string&filename); //将结果写到某个文件里面
    string dealWord(const string &word);
private:
    vector<Record> _dict;
    char*_pdata = nullptr;
};
//<< 运算符重载
ofstream &operator <<(ofstream &os,Record &res){
    os<<"world = "<<res._word<<" "<<"frequency = "<<res._frequency<<endl;
}

void Dictionary::read(const string&filename){
    ifstream ifs(filename,std::ios::ate); //从文件末尾打开
    if(!ifs){
        cerr<<"ifs open is fail!"<<endl;
        return;
    }
    //获取长度
    long length = ifs.tellg();//获取文件长度
    //cout<<length<<endl;
    //打印字符串
    _pdata = new char[length+1]();
    //需要将游标放到开头
    ifs.seekg(0,std::ios::beg);
    ifs.read(_pdata,length);
    //cout<<_pdata<<endl;
}

string Dictionary::dealWord(const string &word)
{
    for(size_t idx = 0; idx != word.size(); ++idx)
    {
        if(!isalpha(word[idx]))
        {
            return string("-1");//以空串进行替换
        }
    }
    return word;
}

void Dictionary::reFind(const char*world){
    string contnet(_pdata);
    string worldTemp =dealWord(world);
    int num = 0;
    int frequency = 0;
    //判断字符串是否合法
    if(strcmp(worldTemp.c_str(),"-1")!=0){
        while(1){
                size_t pos = contnet.find(world,num); //这里的0应该要更新，是下一次的
                if(pos == std::string::npos){
                cout<<"not found\n";
                break;
            }
            else{
                frequency++;
                cout<<frequency<<endl;
                cout<<pos<<endl;
                num = pos + strlen(world);
            }
        }
    //记录单词
    Record res;
    res._word = worldTemp;
    res._frequency = frequency;
    _dict.push_back(res); //压榨操作
    }
    else {
        cout<<"This is an illegal word"<<endl;
    }
    return;

}

void Dictionary::store(const string&filename){
    //读取到文件中
    ofstream ofs(filename,std::ios::app);;//追加写入操作
    for(auto &world : _dict){
        ofs<<world;
    }
    ofs.close();
}

int main(){
    Dictionary dic;
    //dic.read("The_Holy_Bible.txt");
    dic.read("file1.txt");
    dic.reFind("beginning");
    dic.store("file1.log");
    //dic.reFind("firmament");
    //dic.reFind("evening");
    //dic.reFind("absc???");
    //dic.store("world.txt");
    return 0;
}